#!/bin/bash

set -e # 脚本遇到错误立即退出

export ROOT_DIR="$(pwd)"
export WATCHDOG_DIR="${ROOT_DIR}/src"
export PLUGIN_DIR="${ROOT_DIR}/plugin"
export DRIVER_SRC_DIR="${ROOT_DIR}/driver"
export PACKAGE_DIR="${ROOT_DIR}/build"
export SYSBIN_DIR="${PACKAGE_DIR}/srv/sysbin/watchDog"
export PACKAGE_NAME="DGap_V1.1_R1_Patch_17"
export COMPILE_ARGS="-j1"


function build_plugin() {
    sh ${PLUGIN_DIR}/build.sh
}

function build_drvier() {
    sh ${DRIVER_SRC_DIR}/build.sh
}

function build_watchdog() {
    BUILD_DIR="${WATCHDOG_DIR}/build"

    mkdir -p ${BUILD_DIR}
    cd ${BUILD_DIR}
    cmake ..
    make ${COMPILE_ARGS}
    if [ $? -ne 0 ]; then
        echo "compile watchDog failure"
        exit 1
    fi

    mkdir -p "${SYSBIN_DIR}"
    \cp -f watchDog "${SYSBIN_DIR}"
    cd -
    echo "build_watchdog sucessfully"
}

function build_package() {
    cd ${PACKAGE_DIR}
    find . -type f -exec chmod +x {} \;
    rm -rf "${PACKAGE_NAME}_"* md5List.txt readme.xml
    sh buildPatchPackage_zip.sh ${PACKAGE_NAME}
    echo "build_package sucessfully"
    cd -
}

function build_main()
{
    case $1 in
        all)
            build_plugin
            build_watchdog
            build_package
        ;;
        plugin)
            build_plugin
        ;;
        driver)
            build_drvier
        ;;
        watchdog)
            build_watchdog
        ;;
        package)
            build_package
        ;;
    esac
}

build_main $1

exit 0
